/**
 * 系统管理相关API接口
 */

import { request, mockSuccess, mockError } from '@/utils/request'

/**
 * 获取系统配置
 * @returns {Promise} 系统配置
 */
export const getSystemConfig = () => {
  return request.get('/system/config', {}, {}, () => {
    return mockSuccess({
      // 基础配置
      basic: {
        systemName: '基金测试H5系统',
        systemVersion: '1.0.0',
        systemLogo: '/images/logo.png',
        systemDescription: '这是一个基金测试H5系统',
        companyName: '测试公司',
        companyAddress: '北京市朝阳区测试街道123号',
        companyPhone: '400-123-4567',
        companyEmail: 'contact@example.com',
        icp: '京ICP备12345678号',
        copyright: '© 2024 测试公司 版权所有'
      },
      // 功能配置
      features: {
        enableUserRegister: true,
        enableUserLogin: true,
        enableCardManagement: true,
        enableMediationService: true,
        enableNoticeSystem: true,
        enableStoreManagement: true,
        enableFileUpload: true,
        enableComments: true,
        enableRating: true,
        enableSearch: true
      },
      // 安全配置
      security: {
        passwordMinLength: 6,
        passwordMaxLength: 20,
        passwordRequireNumber: true,
        passwordRequireLetter: true,
        passwordRequireSymbol: false,
        loginMaxAttempts: 5,
        loginLockDuration: 30, // 分钟
        sessionTimeout: 120, // 分钟
        enableCaptcha: true,
        enableTwoFactor: false
      },
      // 文件配置
      file: {
        maxFileSize: 10 * 1024 * 1024, // 10MB
        maxImageSize: 5 * 1024 * 1024, // 5MB
        allowedImageTypes: ['jpg', 'jpeg', 'png', 'gif', 'webp'],
        allowedDocumentTypes: ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'txt'],
        uploadPath: '/uploads/',
        enableImageCompress: true,
        imageQuality: 0.8
      },
      // 通知配置
      notification: {
        enableEmailNotification: true,
        enableSmsNotification: true,
        enablePushNotification: true,
        emailProvider: 'smtp',
        smsProvider: 'aliyun',
        pushProvider: 'jpush'
      },
      // 主题配置
      theme: {
        primaryColor: '#1890ff',
        successColor: '#52c41a',
        warningColor: '#faad14',
        errorColor: '#f5222d',
        fontSize: 14,
        borderRadius: 4,
        enableDarkMode: true,
        defaultTheme: 'light'
      }
    })
  })
}

/**
 * 更新系统配置
 * @param {object} data - 配置数据
 * @returns {Promise} 更新结果
 */
export const updateSystemConfig = (data) => {
  return request.put('/system/config', data, {}, () => {
    return mockSuccess(null, '系统配置更新成功')
  })
}

/**
 * 获取系统信息
 * @returns {Promise} 系统信息
 */
export const getSystemInfo = () => {
  return request.get('/system/info', {}, {}, () => {
    return mockSuccess({
      system: {
        name: '基金测试H5系统',
        version: '1.0.0',
        buildTime: '2024-01-15 10:00:00',
        environment: 'production',
        uptime: '15天3小时45分钟',
        startTime: new Date(Date.now() - 15 * 24 * 60 * 60 * 1000).toISOString()
      },
      server: {
        os: 'Linux Ubuntu 20.04',
        cpu: 'Intel Xeon E5-2680 v4',
        memory: '16GB',
        disk: '500GB SSD',
        network: '1000Mbps',
        location: '北京机房'
      },
      database: {
        type: 'MySQL',
        version: '8.0.25',
        size: '2.5GB',
        tables: 45,
        connections: 12,
        status: 'running'
      },
      cache: {
        type: 'Redis',
        version: '6.2.6',
        memory: '512MB',
        keys: 1250,
        hitRate: '95.6%',
        status: 'running'
      },
      performance: {
        cpuUsage: '25.6%',
        memoryUsage: '68.9%',
        diskUsage: '45.2%',
        networkIn: '125MB/s',
        networkOut: '89MB/s',
        responseTime: '156ms'
      }
    })
  })
}

/**
 * 获取系统日志
 * @param {object} params - 查询参数
 * @returns {Promise} 系统日志
 */
export const getSystemLogs = (params = {}) => {
  return request.get('/system/logs', params, {}, (queryParams) => {
    const { page = 1, pageSize = 20, level, keyword, startTime, endTime } = queryParams
    
    const mockLogs = Array.from({ length: 100 }, (_, index) => ({
      id: index + 1,
      level: ['info', 'warn', 'error', 'debug'][Math.floor(Math.random() * 4)],
      message: `系统日志消息${index + 1}`,
      module: ['user', 'card', 'mediation', 'notice', 'store', 'system'][Math.floor(Math.random() * 6)],
      userId: Math.random() > 0.5 ? Math.floor(Math.random() * 100) + 1 : null,
      userName: Math.random() > 0.5 ? `用户${Math.floor(Math.random() * 100) + 1}` : null,
      ip: `192.168.1.${Math.floor(Math.random() * 255) + 1}`,
      userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
      url: `/api/test/${index + 1}`,
      method: ['GET', 'POST', 'PUT', 'DELETE'][Math.floor(Math.random() * 4)],
      statusCode: Math.random() > 0.9 ? 500 : 200,
      responseTime: Math.floor(Math.random() * 1000) + 50,
      createTime: new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toISOString(),
      details: {
        requestId: `req_${Date.now()}_${index}`,
        traceId: `trace_${Date.now()}_${index}`,
        stack: index % 10 === 0 ? 'Error stack trace...' : null
      }
    }))
    
    // 过滤数据
    let filteredLogs = mockLogs
    if (level) {
      filteredLogs = filteredLogs.filter(log => log.level === level)
    }
    if (keyword) {
      filteredLogs = filteredLogs.filter(log => 
        log.message.includes(keyword) || 
        log.module.includes(keyword) ||
        (log.userName && log.userName.includes(keyword))
      )
    }
    if (startTime) {
      filteredLogs = filteredLogs.filter(log => new Date(log.createTime) >= new Date(startTime))
    }
    if (endTime) {
      filteredLogs = filteredLogs.filter(log => new Date(log.createTime) <= new Date(endTime))
    }
    
    // 排序：按时间倒序
    filteredLogs.sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
    
    // 分页
    const total = filteredLogs.length
    const start = (page - 1) * pageSize
    const end = start + pageSize
    const list = filteredLogs.slice(start, end)
    
    return mockSuccess({
      list,
      total,
      page: Number(page),
      pageSize: Number(pageSize),
      totalPages: Math.ceil(total / pageSize)
    })
  })
}

/**
 * 清理系统日志
 * @param {object} data - 清理参数
 * @returns {Promise} 清理结果
 */
export const clearSystemLogs = (data) => {
  return request.delete('/system/logs', data, () => {
    const { days = 30 } = data
    return mockSuccess(null, `成功清理${days}天前的系统日志`)
  })
}

/**
 * 获取操作日志
 * @param {object} params - 查询参数
 * @returns {Promise} 操作日志
 */
export const getOperationLogs = (params = {}) => {
  return request.get('/system/operation-logs', params, {}, (queryParams) => {
    const { page = 1, pageSize = 20, module, action, userId, keyword } = queryParams
    
    const mockLogs = Array.from({ length: 80 }, (_, index) => ({
      id: index + 1,
      module: ['user', 'card', 'mediation', 'notice', 'store'][Math.floor(Math.random() * 5)],
      action: ['create', 'update', 'delete', 'view', 'export'][Math.floor(Math.random() * 5)],
      actionName: ['创建', '更新', '删除', '查看', '导出'][Math.floor(Math.random() * 5)],
      description: `用户执行了${['创建', '更新', '删除', '查看', '导出'][Math.floor(Math.random() * 5)]}操作`,
      userId: Math.floor(Math.random() * 50) + 1,
      userName: `用户${Math.floor(Math.random() * 50) + 1}`,
      ip: `192.168.1.${Math.floor(Math.random() * 255) + 1}`,
      userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
      targetId: Math.floor(Math.random() * 1000) + 1,
      targetType: ['user', 'card', 'mediation', 'notice'][Math.floor(Math.random() * 4)],
      oldData: index % 5 === 0 ? { name: '旧数据', status: 1 } : null,
      newData: index % 5 === 0 ? { name: '新数据', status: 2 } : null,
      result: Math.random() > 0.1 ? 'success' : 'failed',
      resultName: Math.random() > 0.1 ? '成功' : '失败',
      errorMessage: Math.random() > 0.9 ? '操作失败：权限不足' : null,
      duration: Math.floor(Math.random() * 1000) + 50,
      createTime: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString()
    }))
    
    // 过滤数据
    let filteredLogs = mockLogs
    if (module) {
      filteredLogs = filteredLogs.filter(log => log.module === module)
    }
    if (action) {
      filteredLogs = filteredLogs.filter(log => log.action === action)
    }
    if (userId) {
      filteredLogs = filteredLogs.filter(log => log.userId === Number(userId))
    }
    if (keyword) {
      filteredLogs = filteredLogs.filter(log => 
        log.description.includes(keyword) || 
        log.userName.includes(keyword)
      )
    }
    
    // 排序：按时间倒序
    filteredLogs.sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
    
    // 分页
    const total = filteredLogs.length
    const start = (page - 1) * pageSize
    const end = start + pageSize
    const list = filteredLogs.slice(start, end)
    
    return mockSuccess({
      list,
      total,
      page: Number(page),
      pageSize: Number(pageSize),
      totalPages: Math.ceil(total / pageSize)
    })
  })
}

/**
 * 获取系统统计数据
 * @param {object} params - 查询参数
 * @returns {Promise} 统计数据
 */
export const getSystemStats = (params = {}) => {
  return request.get('/system/stats', params, {}, () => {
    return mockSuccess({
      overview: {
        totalUsers: 1250,
        activeUsers: 890,
        totalCards: 3456,
        activeCards: 2890,
        totalMediations: 567,
        totalNotices: 234,
        totalStores: 89,
        totalFiles: 1567
      },
      userStats: {
        newUsersToday: 12,
        newUsersThisWeek: 89,
        newUsersThisMonth: 345,
        activeUsersToday: 156,
        activeUsersThisWeek: 678,
        activeUsersThisMonth: 890
      },
      systemHealth: {
        cpuUsage: 25.6,
        memoryUsage: 68.9,
        diskUsage: 45.2,
        networkUsage: 12.5,
        databaseConnections: 12,
        cacheHitRate: 95.6,
        responseTime: 156,
        errorRate: 0.5
      },
      dailyStats: Array.from({ length: 30 }, (_, index) => ({
        date: new Date(Date.now() - (29 - index) * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
        users: Math.floor(Math.random() * 200) + 100,
        cards: Math.floor(Math.random() * 100) + 50,
        mediations: Math.floor(Math.random() * 20) + 5,
        notices: Math.floor(Math.random() * 10) + 2,
        files: Math.floor(Math.random() * 50) + 20
      })),
      moduleStats: [
        { module: 'user', name: '用户管理', usage: 89.5, requests: 15680 },
        { module: 'card', name: '卡片管理', usage: 76.3, requests: 12450 },
        { module: 'mediation', name: '调解服务', usage: 45.8, requests: 5670 },
        { module: 'notice', name: '通知公告', usage: 34.2, requests: 3450 },
        { module: 'store', name: '商店管理', usage: 23.6, requests: 2340 }
      ]
    })
  })
}

/**
 * 系统备份
 * @param {object} data - 备份参数
 * @returns {Promise} 备份结果
 */
export const systemBackup = (data) => {
  return request.post('/system/backup', data, {}, (params) => {
    const { type = 'full', description = '' } = params
    
    return mockSuccess({
      id: Date.now(),
      type,
      typeName: type === 'full' ? '完整备份' : '增量备份',
      description,
      filename: `backup_${type}_${new Date().toISOString().split('T')[0]}.sql`,
      size: Math.floor(Math.random() * 1000000000) + 100000000, // 100MB-1GB
      status: 'processing',
      statusName: '备份中',
      progress: 0,
      startTime: new Date().toISOString(),
      estimatedTime: Math.floor(Math.random() * 30) + 10 // 10-40分钟
    }, '系统备份已开始')
  })
}

/**
 * 获取备份列表
 * @param {object} params - 查询参数
 * @returns {Promise} 备份列表
 */
export const getBackupList = (params = {}) => {
  return request.get('/system/backups', params, {}, (queryParams) => {
    const { page = 1, pageSize = 20 } = queryParams
    
    const mockBackups = Array.from({ length: 30 }, (_, index) => ({
      id: index + 1,
      type: Math.random() > 0.5 ? 'full' : 'incremental',
      typeName: Math.random() > 0.5 ? '完整备份' : '增量备份',
      description: `系统备份${index + 1}`,
      filename: `backup_${Math.random() > 0.5 ? 'full' : 'incremental'}_${new Date(Date.now() - index * 24 * 60 * 60 * 1000).toISOString().split('T')[0]}.sql`,
      size: Math.floor(Math.random() * 1000000000) + 100000000,
      status: ['completed', 'failed', 'processing'][Math.floor(Math.random() * 3)],
      statusName: ['已完成', '失败', '进行中'][Math.floor(Math.random() * 3)],
      progress: 100,
      startTime: new Date(Date.now() - index * 24 * 60 * 60 * 1000).toISOString(),
      endTime: new Date(Date.now() - index * 24 * 60 * 60 * 1000 + Math.random() * 60 * 60 * 1000).toISOString(),
      duration: Math.floor(Math.random() * 30) + 10,
      downloadUrl: `/downloads/backup_${index + 1}.sql`,
      createTime: new Date(Date.now() - index * 24 * 60 * 60 * 1000).toISOString()
    }))
    
    // 排序：按时间倒序
    mockBackups.sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
    
    // 分页
    const total = mockBackups.length
    const start = (page - 1) * pageSize
    const end = start + pageSize
    const list = mockBackups.slice(start, end)
    
    return mockSuccess({
      list,
      total,
      page: Number(page),
      pageSize: Number(pageSize),
      totalPages: Math.ceil(total / pageSize)
    })
  })
}

/**
 * 系统恢复
 * @param {number} backupId - 备份ID
 * @returns {Promise} 恢复结果
 */
export const systemRestore = (backupId) => {
  return request.post(`/system/restore/${backupId}`, {}, {}, () => {
    return mockSuccess({
      id: Date.now(),
      backupId: Number(backupId),
      status: 'processing',
      statusName: '恢复中',
      progress: 0,
      startTime: new Date().toISOString(),
      estimatedTime: Math.floor(Math.random() * 20) + 5 // 5-25分钟
    }, '系统恢复已开始')
  })
}

/**
 * 获取系统通知
 * @returns {Promise} 系统通知
 */
export const getSystemNotifications = () => {
  return request.get('/system/notifications', {}, {}, () => {
    return mockSuccess([
      {
        id: 1,
        type: 'info',
        title: '系统维护通知',
        content: '系统将于今晚23:00-01:00进行维护，请提前保存数据',
        level: 'medium',
        read: false,
        createTime: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString()
      },
      {
        id: 2,
        type: 'warning',
        title: '磁盘空间警告',
        content: '系统磁盘使用率已达到85%，请及时清理',
        level: 'high',
        read: false,
        createTime: new Date(Date.now() - 4 * 60 * 60 * 1000).toISOString()
      },
      {
        id: 3,
        type: 'success',
        title: '备份完成',
        content: '系统备份已成功完成',
        level: 'low',
        read: true,
        createTime: new Date(Date.now() - 6 * 60 * 60 * 1000).toISOString()
      }
    ])
  })
}

/**
 * 标记通知为已读
 * @param {number} id - 通知ID
 * @returns {Promise} 标记结果
 */
export const markNotificationRead = (id) => {
  return request.put(`/system/notifications/${id}/read`, {}, {}, () => {
    return mockSuccess(null, '通知已标记为已读')
  })
}

/**
 * 清理系统缓存
 * @param {object} data - 清理参数
 * @returns {Promise} 清理结果
 */
export const clearSystemCache = (data) => {
  return request.delete('/system/cache', data, () => {
    const { type = 'all' } = data
    return mockSuccess(null, `${type === 'all' ? '全部' : type}缓存清理成功`)
  })
}

/**
 * 重启系统服务
 * @param {string} service - 服务名称
 * @returns {Promise} 重启结果
 */
export const restartSystemService = (service) => {
  return request.post(`/system/services/${service}/restart`, {}, {}, () => {
    return mockSuccess(null, `${service}服务重启成功`)
  })
}